// 获取元素
const login = document.querySelector('.login')
const register = document.querySelector('.register')
const loginForm = login.querySelector('form')
const registerForm = register.querySelector('form')

// 点击切换注册和登录盒子的显示与隐藏
login.querySelector('.goRegister').addEventListener("click", () => {
    login.style.display = 'none'
    register.style.display = 'block'
})
register.querySelector('.goLogin').addEventListener('click', () => {
    login.style.display = 'block'
    register.style.display = 'none'
})

// 封装用户名和密码判断函数
function regtest(data) {
    if (data.username.length < 2 || data.username.length > 15) {
        return alert('用户名为长度2~15位')
    }
    if (data.password.length < 6 || data.password.length > 15) {
        return alert('密码为长度6~15位')
    }
}

// 点击登录功能
login.querySelector('.btn-primary').addEventListener('click', async e => {
    e.preventDefault()
    const data = serialize(loginForm, { hash: true, empty: true })
    regtest(data)
    try {
        const res = await axios({
            url: "/api/login",
            method: 'post',
            data
        })
        console.log(res.data);
        localStorage.setItem('myToken', res.data.token)
        localStorage.setItem('username', data.username)
        location.href = './index.html'
    } catch (error) {
        console.dir(error);
    }
})

// 点击注册功能
register.querySelector('.btn-primary').addEventListener('click', async e => {
    e.preventDefault()
    const data = serialize(registerForm, { hash: true, empty: true })
    regtest(data)
    try {
        const res = await axios({
            url: "/api/register",
            method: 'post',
            data
        })
        console.log(res);
    } catch (error) {
        console.dir(error);
    }
})